import { message } from 'ant-design-vue'

/**
 * axios请求结果统一处理
 *
 * @param {Object} response axios请求响应结构
 */
export const handleResult = response => {
  const { data } = response
  const { code, msg } = data

  if (code === 0) {
    message.error(msg)
  }

  return {
    success (cb) {
      if (code !== 0) {
        cb(data)
      }
      return this
    },
    fail (cb) {
      if (code === 0) {
        cb(data)
      }
      return this
    },
    finally (cb) {
      cb(data)
      return this
    }
  }
}

/**
 * 深拷贝对象
 *
 * @param {Object} obj 对象
 * @returns 拷贝相同的对象
 */
export const deepClone = obj => {
  return JSON.parse(JSON.stringify(obj))
}

/**
 * 格式化时间戳
 *
 * @param {String} ts 时间戳
 */
export const formateTimestamp = ts => {
  const date = new Date(Number(ts))

  const padStart = (num, n) => {
    return String(num).padStart(n, '0')
  }

  const YYYY = padStart(date.getFullYear(), 4)
  const MM = padStart(date.getMonth() + 1, 2)
  const DD = padStart(date.getDate(), 2)
  const hh = padStart(date.getHours(), 2)
  const mm = padStart(date.getMinutes(), 2)
  const ss = padStart(date.getSeconds(), 2)

  return `${YYYY}-${MM}-${DD} ${hh}:${mm}:${ss}`
}
